import React, { memo, useCallback, useEffect, useRef, useState } from "react";
import { useSelector, useDispatch, shallowEqual } from "react-redux";
import { Carousel } from "antd";

import { getTopBannersAction } from "./store/actionCreators";
import { BannerWrapper, BannerLeft, BannerRight, BannerControls } from "./style";

export default memo(function TopBanner() {
  const [curIndex, setCurIndex] = useState(0);

  const { topBanners } = useSelector(
    state => ({
      // topBanners: state.get("recommend").get("topBanners"),
      topBanners: state.getIn(["topBanner", "topBanners"]),
    }),
    shallowEqual
  );

  const carouselRef = useRef();

  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(getTopBannersAction());
  }, [dispatch]);

  const carouselChange = useCallback((from, to) => {
    setCurIndex(to);
  }, []);

  const bgImage = topBanners && topBanners[curIndex] && `${topBanners[curIndex].imageUrl}?imageView&blur=40x20`;

  return (
    <BannerWrapper bgImage={bgImage}>
      <div className="wrap-v2 banner">
        <BannerLeft>
          <Carousel effect="fade" autoplay dots={{ className: "dots" }} ref={carouselRef} beforeChange={carouselChange}>
            {topBanners &&
              topBanners.map((item, index) => {
                return (
                  <a href={item.url} key={item.imageUrl} className="">
                    <img className="img-item" src={item.imageUrl} alt={item.typeTitle} />
                  </a>
                );
              })}
          </Carousel>
        </BannerLeft>
        <BannerRight>
          <p className="tips">PC 安卓 iPhone WP iPad Mac 六大客户端</p>
          <a className="download" href="https://music.163.com/#/download">
            下载
          </a>
        </BannerRight>
        <BannerControls>
          <div className="btn left" onClick={e => carouselRef.current.prev()}></div>
          <div className="btn right" onClick={e => carouselRef.current.next()}></div>
        </BannerControls>
      </div>
    </BannerWrapper>
  );
});
